import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/app_config.dart';

/// 本地存储工具类
class StorageUtil {
  static SharedPreferences? _prefs;
  
  /// 初始化
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }
  
  /// Token 相关
  static String? getToken() {
    return _prefs?.getString(AppConfig.tokenKey);
  }
  
  static Future<bool> setToken(String token) async {
    return await _prefs?.setString(AppConfig.tokenKey, token) ?? false;
  }
  
  static Future<bool> removeToken() async {
    return await _prefs?.remove(AppConfig.tokenKey) ?? false;
  }
  
  /// 用户信息
  static Map<String, dynamic>? getUserInfo() {
    final userInfoStr = _prefs?.getString(AppConfig.userInfoKey);
    if (userInfoStr != null) {
      return jsonDecode(userInfoStr);
    }
    return null;
  }
  
  static Future<bool> setUserInfo(Map<String, dynamic> userInfo) async {
    return await _prefs?.setString(AppConfig.userInfoKey, jsonEncode(userInfo)) ?? false;
  }
  
  static Future<bool> removeUserInfo() async {
    return await _prefs?.remove(AppConfig.userInfoKey) ?? false;
  }
  
  /// 用户设置
  static Map<String, dynamic> getSettings() {
    final settingsStr = _prefs?.getString(AppConfig.settingsKey);
    if (settingsStr != null) {
      return jsonDecode(settingsStr);
    }
    // 默认设置
    return {
      'defaultLanguage': 'cn',
      'playbackSpeed': 1.0,
      'autoPlayNext': false,
      'wifiOnly': false,
      'darkMode': true,
      'notificationEnabled': true,
      'notificationTime': 'all',
    };
  }
  
  static Future<bool> setSettings(Map<String, dynamic> settings) async {
    return await _prefs?.setString(AppConfig.settingsKey, jsonEncode(settings)) ?? false;
  }
  
  /// 清除所有数据
  static Future<bool> clear() async {
    return await _prefs?.clear() ?? false;
  }
  
  /// 判断是否已登录
  static bool isAuthenticated() {
    return getToken() != null;
  }
  
  /// 登出
  static Future<void> logout() async {
    await removeToken();
    await removeUserInfo();
  }
}

